// Copyright 2009, Lucid Technics, LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in
// writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

importClass(Packages.org.tmatesoft.svn.core.SVNDirEntry);
importClass(Packages.org.tmatesoft.svn.core.SVNURL);
importClass(Packages.org.tmatesoft.svn.core.io.SVNRepository);
importClass(Packages.org.tmatesoft.svn.core.io.SVNRepositoryFactory);
importClass(Packages.org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory);
importClass(Packages.java.io.File);

var repositoryRoot = SERVLET.getServletConfig().getInitParameter("rr.repository.root");

CONTENT_CONTEXT.type = "application/xhtml+xml";
FSRepositoryFactory.setup();

try
{
	var name = REST_CONTEXT.getIdValue("svnrepository.name");
	var file = new File(repositoryRoot, name);
	var resourceExists = true;
	
	if (h.isDefined(file) === true &&
		  file.exists() === true &&
		  file.isDirectory() === true)
	{
		var url = SVNURL.parseURIDecoded("file:///" + file.getAbsolutePath().replaceAll("^/", ""));
		var repository = SVNRepositoryFactory.create(url);
		var path = repository.getRepositoryRoot(true).getPath();
		var info = repository.info("/", 0);

		if (h.isDefined(info) === true)
		{
			var svnRepository = h.ar();
			
			svnRepository.name = file.name;
			svnRepository.root = repositoryRoot;
			svnRepository.URL = url;
			svnRepository.lastModifiedDate = info.date;
			svnRepository.status = "ACTIVE";
			svnRepository.revision = info.revision;
			svnRepository.lastAuthor = info.author;

			CONTENT_CONTEXT.content = svnRepository.toRdfa();
		}
		else
		{
			resourceExists = false;
		}
	}
	else
	{
		resourceExists = false;
	}

	if (resourceExists === false)
	{
		CONTENT_CONTEXT.content = h.msg404();
	}
}
catch(e)
{
	LOG.error("Encountered exception:" + e + " while trying to get repository list.");
	CONTENT_CONTEXT.content = h.msg500();
}